<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto">
			<el-card shadow="hover" class="pageQueryBoxArea mb10">
				<el-form :model="state.param" :inline="true">
					<el-form-item label="选择门店">
						<el-select v-model="state.param.source" placeholder="请选择订单来源">
							<el-option v-for="item in state.query.orderSource" :key="item.value"
								:label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				
					<el-form-item label="选择员工">
						<el-select v-model="state.param.mode" placeholder="请选择门店属性" @change="modeChange()">
							<el-option v-for="item in state.query.storeType" :key="item.value"
								:label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				
					<el-form-item label="选择标签">
						<el-select v-model="state.param.nodeId" placeholder="请选择门店" @change="search()">
							<el-option v-for="item in state.query.storeList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-form-item>
				
					<el-form-item label="会员状态">
						<el-select v-model="state.param.channel" placeholder="请选择销售终端" @change="search()">
							<el-option v-for="item in state.query.saleChannel" :key="item.value" :label="item.name"
								:value="item.value" />
						</el-select>
					</el-form-item>
				
					<el-form-item label="订单状态">
						<el-select v-model="state.param.status" placeholder="请选择订单状态" @change="search()">
							<el-option v-for="item in state.query.orderStatus" :key="item.value"
								:label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				
					<el-form-item label="选择日期">
						<el-date-picker v-model="state.param.dateTime" type="daterange" unlink-panels
							format="YYYY/MM/DD" value-format="YYYY-MM-DD" range-separator="-" :disabled-date="disabledDate"
							start-placeholder="开始日期" end-placeholder="结束日期" />
					</el-form-item>
					<el-form-item label="信息搜索">
						<el-input v-model="state.param.keyword" placeholder="请输入关键字搜索" clearable></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="search()">
							<el-icon>
								<ele-Search />
							</el-icon> 搜 索
						</el-button>
						<el-button type="primary" @click="search()">
							<el-icon>
								<ele-Refresh />
							</el-icon> 重 置
						</el-button>
					</el-form-item>
				</el-form>
			</el-card>
			<el-card shadow="hover" style="display: flex;flex-direction: column;flex: 1;height: inherit;">
				<section style="display: flex;flex-direction: column; flex: 1;height: inherit;">
					<el-table :data="state.tableData">
						<el-table-column  label="ID" width="90">
							<template #default="scope">
								<span> {{ scope.row.userId }}</span>
							</template>
						</el-table-column>
						<el-table-column label="头像" width="80">
							<template #default="scope">
								<section style="width:64px; height: 64px;border-radius: 5px;">
									<el-image style="width:64px; height: 64px;border-radius: 5px;" :src="scope.row.imageUrl" fit="cover" />
								</section>
							</template>
						</el-table-column>
						<el-table-column  label="姓名/昵称" show-overflow-tooltip>
							<template #default="scope">
								<span> {{ scope.row.familyName }}{{ scope.row.userName }}</span>
							</template>
						</el-table-column>
						<el-table-column label="手机">
							<template #default="scope">
								<span> 188****8888 </span>
							</template>
						</el-table-column>
						<el-table-column label="生日">
							<template #default="scope">
								<span> {{ scope.row.birthday }} </span>
							</template>
						</el-table-column>
						<el-table-column label="会员等级">
							<template #default="scope">
								<span> {{ scope.row.levelName }} </span>
							</template>
						</el-table-column>
						<el-table-column label="付费会员">
							<template #default="scope">
								<span>暂无数据</span>
							</template>
						</el-table-column>
						<el-table-column label="综合消费">
							<template  #default="scope">
								<span> {{ scope.row.balance }} </span>
								<span> {{ scope.row.handselBalance }} </span>
							</template>
						</el-table-column>
						<el-table-column label="综合余额">
							<template #default="scope">
								<span>暂无数据</span>
							</template>
						</el-table-column>
						<el-table-column label="欠款金额">
							<template #default="scope">
								<span> {{ scope.row.arrears }} </span>
							</template>
						</el-table-column>
						<el-table-column label="可用积分">
							<template #default="scope">
								<span> {{ scope.row.points }} </span>
							</template>
						</el-table-column>
						<el-table-column label="来源">
							<template #default="scope">
								<span> x 天 </span>
							</template>
						</el-table-column>
						<el-table-column label="距今到店">
							<template #default="scope">
								<span> x 天 </span>
							</template>
						</el-table-column>
						<el-table-column label="操作">
							<template #default="scope">
								<el-button text type="primary" @click="goToDetails(scope.row)" >详情</el-button> | 
								<el-dropdown>
									<span>
										<el-button  text type="primary">更多</el-button>
									</span>
									<template #dropdown>
										<el-dropdown-menu>
											<el-dropdown-item>设置分组</el-dropdown-item>
											<el-dropdown-item>设置标签</el-dropdown-item>
											<el-dropdown-item>修改归属</el-dropdown-item>
											<el-dropdown-item>修改推荐人</el-dropdown-item>
											<el-dropdown-item>修改积分</el-dropdown-item>
											<el-dropdown-item>消费数据</el-dropdown-item>
											<el-dropdown-item>财务数据</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
							</template>
						</el-table-column>
						<template #empty>
							<el-empty description="暂无数据" />
						</template>
					</el-table>
					<el-row justify="end">
						<el-col :span="24" class="flex-end-center">
							<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange"
								class="mt15" :pager-count="5" :page-sizes="[10, 20, 30,50,100,500,1000]"
								v-model:current-page="state.param.pageNum" background v-model:page-size="state.param.pageSize"
								layout="total, sizes, prev, pager, next, jumper" :total="state.total">
							</el-pagination>
						</el-col>
					</el-row>
				</section>
			</el-card>
		</div>
		<changePriceDialog ref="changePriceDialogRef" @refresh="getOrderList()" />
		<deliverGoodDialog ref="deliverGoodDialogRef" @refresh="getOrderList()" />
	</div>
</template>

<script setup lang="ts" name="saleIndex">
import { reactive,onMounted,ref,defineAsyncComponent} from 'vue';
import { useRouter } from 'vue-router';
import type { storeNodeListData, channelListData } from "/@/types/order";
import type { memberUserListData } from "/@/types/member";
import { storeNodeList, channelList, orderAddNote, orderCancel } from '/@/api/order';
import { userList } from '/@/api/member';

import { ElMessageBox, ElMessage, TabsPaneContext } from 'element-plus';
// 引入组件
const changePriceDialog = defineAsyncComponent(() => import('/@/views/order/sale/changePriceDialog.vue'));
const deliverGoodDialog = defineAsyncComponent(() => import('/@/views/order/sale/deliverGoodDialog.vue'));


const router = useRouter();
// 定义变量内容
const changePriceDialogRef = ref();
const deliverGoodDialogRef = ref();
const state = reactive({
	param: {
		type: 4,
		source: 0, // 0 门店 2 线上 //设置不了得值是哪个？
		mode: null, // 门店类型  null(默认) 全部 0 直营  1 加盟
		nodeId: null, // 门店id
		// 销售渠道
		channel: null,
		status: null,
		// 支付方式
		dateTime: [],
		startTime: "",
		endTime: "",
		timeInterval: 3,
		keyword: "",
		pageNum: 1,
		pageSize: 10,
		change: 999,
	},
	query: {
		orderSource: [
			{ value: 0, label: '门店订单' },
		],
		storeType: [
			{ value: null, label: '全部' },
			{ value: 0, label: '直营' },
			{ value: 1, label: '加盟' }
		],
		storeList: [] as Array<storeNodeListData>,
		orderStatus: [
			{ value: null, label: '全部' },
			{ value: 4, label: '已服务' },
			{ value: 14, label: '已撤销' },
		],
		saleChannel: [] as Array<channelListData>,
		orderType:[
			{ value: 999, label: '全部订单' },
			{ value: 1, label: '换卡服务' },
			{ value: 2, label: '余卡服务' },
		]
	},
	loading: false,
	total: 0,
	tableData: [] as Array<memberUserListData>
});

onMounted(() => {
	// 获取订单列表
	getUserList();
	// 获取门店列表
	getStoreNodeList();
	// 获取销售渠道列表
	getChannelList();
})


const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 获取订单列表
const getUserList = async () => {
	state.loading = true;
	const { results } = await userList(state.param);
	state.loading = false;
	state.tableData = results.records;
	state.total = results.total;
}

// 搜索
const search = () => {
	console.log(state.param)
	if (state.param.dateTime?.length == 2) {
		state.param.startTime = state.param.dateTime[0]
		state.param.endTime = state.param.dateTime[1]
	}
	state.param.pageNum = 1;
	getUserList()
}

/**
 * 获取销售渠道列表

 */
 const getChannelList = async () => {
	const { results } = await channelList({ source: state.param.source, });
	state.query.saleChannel = results;
	state.param.change = 999
}

// 获取门店列表
/**
 * mode  null /全部   0直营  1加盟
 */
const getStoreNodeList = async () => {
	const { results } = await storeNodeList({ mode: null, current: 1, size: 50 });
	let no1 = [{id:null,name:'全部'}]
	state.query.storeList = [...no1, ...results.records];
}

const handleClick = (tab: TabsPaneContext) => {
	let select = tab.props.name
	if (select != state.param.change) { // 明白 
		console.log(select, state.param.change)
		state.param.pageNum = 1;
		state.param.change = select! as any;  //赋值 赋值是 + select!?  + 代表把字符串转为数字  ！ 是TS里面非空符号
		getUserList();
	}
}

// 会员详情
const goToDetails = (item: any) => {
	console.log(item.userId)
	router.push({
		path: '/member/statistics/details',
		query: { id: item.userId },
	});
};



// 分页点击 条数
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
	getUserList();
};
// 分页点击
const onHandleCurrentChange = (val: number) => {
	state.param.pageNum = val;
	getUserList();
};

// 添加备注
const addNote = (snkey: String) => {
	ElMessageBox.prompt(`商家备注`, '备注', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		inputPattern: /^.+$/,
		inputErrorMessage: '请输入备注',
	}).then(async ({ value }) => {
		let params = {
			snkey: snkey,
			note: value
		}
		let res = await orderAddNote(params);
		console.log(res)
		getUserList();
		ElMessage.success('添加成功');
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消',
		})
	})
}

// 撤销订单
const onRevokeOrder = (id: number, index: number) => {
	ElMessageBox.prompt(
		`您现在操作的是撤销订单，请慎重;该操作会使订单无效，同时用户消费数据、员工业绩、商品销量等相关数据均会撤销（恢复为之前的状态或数据）; 是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		inputPattern: /^.+$/,
		inputErrorMessage: '请输入订单撤销原因',
	}).then(async ({ value }) => {
		let params = {
			id: id,
			reason: value
		}
		let res = await orderCancel(params);
		console.log(res)
		state.tableData[index].status = '已撤销'
		ElMessage.success('撤销成功');
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消',
		})
	})
};
 
// 订单改价
const changePrice = async ( item: any) => {
	changePriceDialogRef.value.openDialog(item);
}

// 订单发货
const deliverFun = (item: any) => {
	deliverGoodDialogRef.value.openDialog(item);
}


// 销售员工过滤器
const rebateListFilters = (item: any) => {
	let arr = item[0].rebateList
	if (Array.isArray(arr)) {
		let newArr = arr.map((obj: { id: any, employee: any, money: any; }) => obj.employee);
		let uniqueArr = [...new Set(newArr)];
		return uniqueArr.join('、')
	} else {
		return '--'
	}
}

// 门店类型切换 (如果不是全部则清空选中门店 以及订单选中状态)
const modeChange = () => {
	if(state.param.mode != null){
		state.param.nodeId = null;
		state.param.status = null;
	}
}
</script>
<style scoped lang="scss">
@import '../../../theme/mixins/index.scss';
:deep(.el-card__body){
	display: flex;
	flex-direction: column;
	flex: 1;
	height: inherit;
	.el-table{
		flex: 1;
		.el-table__inner-wrapper::before{
			background: none !important;
		}
	}
}
</style>
